<template>
  <div class="paper-test-practice">
    <!-- 试卷信息头部 -->
    <el-card class="paper-header">
      <div class="header-wrapper">
        <div class="paper-title">
          <h2>{{ paperInfo.name }}</h2>
          <div class="paper-subtitle">试卷练习</div>
        </div>
        <div class="header-content">
          <div class="paper-stats">
            <div class="stat-item">
              <span class="stat-icon">📝</span>
              <span class="stat-text">总题数: <strong>{{ paperInfo.totalQuestions }}</strong></span>
            </div>
            <div class="stat-item">
              <span class="stat-icon">⏱️</span>
              <span class="stat-text">总时长: <strong>{{ paperInfo.totalDuration }}分钟</strong></span>
            </div>
            <div class="stat-item">
              <span class="stat-icon">✅</span>
              <span class="stat-text">已答: <strong class="answered-count">{{ answeredCount }}题</strong></span>
            </div>
            <div class="stat-item">
              <span class="stat-icon">❓</span>
              <span class="stat-text">未答: <strong class="unanswered-count">{{ unansweredCount }}题</strong></span>
            </div>
          </div>
          <div class="timer-section">
            <div class="countdown-wrapper">
              <span class="countdown-label">剩余时间</span>
              <el-countdown 
                :value="endTime" 
                value-style="color: #409eff; font-size: 20px; font-weight: bold;"
                @finish="onTimeUp"
              />
            </div>
            <el-button @click="goToSettings" icon="Back">返回设置</el-button>
            <el-button type="danger" @click="submitPaper" icon="Select">交卷</el-button>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 主内容区 - 左侧题目区域，右侧答题卡 -->
    <div class="main-content">
      <!-- 题目区域 -->
      <el-card class="question-area">
        <template #header>
          <div class="question-header">
            <span class="question-title-badge">
              <el-icon><Document /></el-icon>
              <span>第{{ getCurrentQuestionContinuousNumber() }}题 (共{{ getSortedQuestions.length }}题)【{{ currentQuestionModule }}】</span>
            </span>
          </div>
        </template>
        
        <!-- 题目内容 -->
        <div class="question-content" v-if="currentQuestion">
          <div class="question-main">
            <div class="question-title-container">
              <h3 class="question-title" v-html="sanitizeQuestionContentHtml(currentQuestion.content)"></h3>
            </div>
            
            <!-- 选项区域 -->
            <div class="options-container">
              <div class="options-area" v-if="currentQuestion.questionType && (currentQuestion.questionType === 'single' || currentQuestion.questionType === 'single_choice' || currentQuestion.questionType === 'multiple' || currentQuestion.questionType === 'multiple_choice')">
                <el-radio-group 
                  v-if="currentQuestion.questionType === 'single' || currentQuestion.questionType === 'single_choice'" 
                  v-model="userAnswers[`${currentQuestion.type}-${currentQuestion.id}`]" 
                  class="options-list"
                >
                  <el-radio 
                    v-for="(option, index) in currentQuestion.options" 
                    :key="index" 
                    :label="String.fromCharCode(65 + index)"
                    class="option-item"
                  >
                    <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                    <span class="option-content" v-html="sanitizeOptionHtml(option.content)"></span>
                  </el-radio>
                </el-radio-group>
                
                <el-checkbox-group 
                  v-else-if="currentQuestion.questionType === 'multiple' || currentQuestion.questionType === 'multiple_choice'" 
                  v-model="userAnswers[`${currentQuestion.type}-${currentQuestion.id}`]" 
                  class="options-list"
                >
                  <el-checkbox 
                    v-for="(option, index) in currentQuestion.options" 
                    :key="index" 
                    :label="String.fromCharCode(65 + index)"
                    class="option-item"
                  >
                    <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                    <span class="option-content" v-html="sanitizeOptionHtml(option.content)"></span>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              
              <!-- 判断题 -->
              <div class="true-false-area" v-else-if="currentQuestion.questionType && (currentQuestion.questionType === 'trueFalse' || currentQuestion.questionType === 'true_false')">
                <el-radio-group v-model="userAnswers[`${currentQuestion.type}-${currentQuestion.id}`]" class="options-list">
                  <el-radio label="true" class="option-item">正确</el-radio>
                  <el-radio label="false" class="option-item">错误</el-radio>
                </el-radio-group>
              </div>
              
              <!-- 填空题 -->
              <div class="fill-blank-area" v-else-if="currentQuestion.questionType && (currentQuestion.questionType === 'fillBlank' || currentQuestion.questionType === 'fill_blank')">
                <el-input 
                  v-model="userAnswers[`${currentQuestion.type}-${currentQuestion.id}`]" 
                  placeholder="请输入答案" 
                  style="width: 300px;"
                />
              </div>
              
              <!-- 简答题 -->
              <div class="short-answer-area" v-else-if="currentQuestion.questionType && (currentQuestion.questionType === 'shortAnswer' || currentQuestion.questionType === 'short_answer')">
                <el-input 
                  v-model="userAnswers[`${currentQuestion.type}-${currentQuestion.id}`]" 
                  type="textarea" 
                  :rows="5" 
                  placeholder="请输入答案"
                />
              </div>
            </div>
          </div>
          
          <!-- 题目解析（如果启用显示答案） -->
          <div class="question-analysis" v-if="showAnswers && currentQuestion.analysis">
            <el-divider />
            <h4>题目解析</h4>
            <div v-html="sanitizeQuestionContentHtml(currentQuestion.analysis)"></div>
          </div>
        
          <!-- 题目导航按钮 -->
          <div class="question-navigation-bottom">
            <div class="navigation-buttons">
              <el-button 
                :disabled="currentQuestionIndex === 0" 
                @click="previousQuestion"
                size="small"
              >
                上一题
              </el-button>
              <el-button 
                :disabled="currentQuestionIndex === getSortedQuestions.length - 1" 
                @click="nextQuestion"
                size="small"
                type="primary"
              >
                下一题
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 答题卡 -->
      <el-card class="answer-sheet">
        <template #header>
          <div class="sheet-header">
            <span class="sheet-title">
              <el-icon><Grid /></el-icon>
              <span>答题卡</span>
            </span>
            <div class="sheet-legend">
              <div class="legend-item">
                <span class="legend-dot answered"></span>
                <span class="legend-text">已答</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot current"></span>
                <span class="legend-text">当前</span>
              </div>
            </div>
          </div>
        </template>
        <div class="sheet-content">
          <!-- 按模块分组显示答题卡 -->
          <div 
            v-for="(moduleQuestions, module) in groupedQuestions" 
            :key="module"
            class="module-section"
          >
            <div class="module-name">
              <span class="module-name-text">{{ getModuleDisplayName(module) }}</span>
              <span class="module-count">{{ moduleQuestions.length }}题</span>
            </div>
            <div class="module-sheet">
              <div 
                v-for="(question, index) in moduleQuestions" 
                :key="`${module}-${question.id}`"
                class="sheet-item"
                :class="getSheetItemClass(question, module, index)"
                @click="onAnswerSheetClick(question.id, module, index)"
              >
                <span class="sheet-item-number">{{ getContinuousQuestionNumber(module, index) }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 交卷确认对话框 -->
    <el-dialog v-model="showSubmitDialog" title="确认交卷" width="400px">
      <p>确定要提交试卷吗？</p>
      <p>答题情况: 已答 {{ answeredCount }} 题，未答 {{ unansweredCount }} 题</p>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSubmitDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSubmit">确认交卷</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import * as paperApi from '@/api/paper'
import * as paperResultApi from '@/api/paperResult'
import * as paperScoreApi from '@/api/paperScore' // 添加试卷分值API导入
import { modifyQuestionContentImageSizeInHTML, modifyOptionImageSizeInHTML } from '@/utils/htmlUtils'
import { addWrongQuestion } from '@/api/wrongQuestions'

// 定义题目数据类型
interface Question {
  id: number
  type: string // 模块类型，如 politics, commonSense 等
  questionType?: string // 题目类型，如 single_choice, multiple_choice 等
  content: string
  options?: { content: string }[]
  correctAnswer?: string
  correctAnswers?: string[]
  analysis?: string
  category?: string // 题目分类，如图形推理等
}

// 定义试卷信息类型
interface PaperInfo {
  id: number
  name: string
  totalDuration: number
  totalQuestions: number
}

// 路由
const route = useRoute()
const router = useRouter()

// 试卷信息
const paperInfo = ref<PaperInfo>({
  id: 0,
  name: '试卷名称',
  totalDuration: 120,
  totalQuestions: 100
})

// 试卷分值信息
const paperScoreInfo = ref<any>(null)

// 试卷题目
const paperQuestions = ref<Question[]>([])

// 用户答案记录 - 修改为使用模块+ID作为键
const userAnswers = reactive<Record<string, any>>({})

// 当前题目索引
const currentQuestionIndex = ref(0)

// 考试结束时间
const endTime = ref(Date.now() + 120 * 60 * 1000) // 默认120分钟

// 显示答案
const showAnswers = ref(false)

// 交卷对话框
const showSubmitDialog = ref(false)

// 当前题目
const currentQuestion = computed(() => {
  return getSortedQuestions.value[currentQuestionIndex.value]
})

// 当前题目模块
const currentQuestionModule = computed(() => {
  if (!currentQuestion.value || !currentQuestion.value.type) return ''
  
  // 优先使用模块映射，如果type是模块类型的话
  const moduleMap: Record<string, string> = {
    'politics': '政治理论',
    'commonSense': '常识判断',
    'language': '言语理解与表达',
    'quantity': '数量关系',
    'judgment': '判断推理',
    'dataAnalysis': '资料分析'
  }
  
  // 题型映射（用于备选显示）
  const questionTypeMap: Record<string, string> = {
    'single': '单选题',
    'multiple': '多选题',
    'trueFalse': '判断题',
    'fillBlank': '填空题',
    'shortAnswer': '简答题',
    'single_choice': '单选题',
    'multiple_choice': '多选题',
    'true_false': '判断题',
    'fill_blank': '填空题',
    'short_answer': '简答题'
  }
  
  // 如果是判断推理模块，需要显示category信息
  if (currentQuestion.value.type === 'judgment') {
    const baseName = moduleMap[currentQuestion.value.type] || '判断推理'
    // 如果题目有category字段，则显示为"判断推理-category"
    if (currentQuestion.value.category) {
      return `${baseName}-${currentQuestion.value.category}`
    }
    // 如果category为空，则默认显示"图形推理"
    return `${baseName}-图形推理`
  }
  
  // 如果type是模块类型，直接返回对应的中文模块名
  if (moduleMap[currentQuestion.value.type]) {
    return moduleMap[currentQuestion.value.type]
  }
  
  // 否则返回题型的中文名（保持原有逻辑作为备选）
  return questionTypeMap[currentQuestion.value.type] || currentQuestion.value.type
})

// 已答题数
const answeredCount = computed(() => {
  return Object.keys(userAnswers).filter(key => userAnswers[key]).length
})

// 未答题数
const unansweredCount = computed(() => {
  return getSortedQuestions.value.length - answeredCount.value
})

// 按模块分组的题目
const groupedQuestions = computed(() => {
  const groups: Record<string, Question[]> = {};
  
  paperQuestions.value.forEach(question => {
    const module = question.type || 'unknown';
    if (!groups[module]) {
      groups[module] = [];
    }
    groups[module].push(question);
  });
  
  // 定义模块顺序: 政治理论、常识、言语、数量关系、判断、资料
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  
  // 按照指定顺序重新组织对象
  const orderedGroups: Record<string, Question[]> = {};
  
  // 先按指定顺序添加模块
  moduleOrder.forEach(module => {
    if (groups[module]) {
      orderedGroups[module] = groups[module];
    }
  });
  
  // 添加其他未在顺序列表中的模块
  Object.keys(groups).forEach(module => {
    if (!moduleOrder.includes(module)) {
      orderedGroups[module] = groups[module];
    }
  });
  
  return orderedGroups;
});

// 获取模块显示名称
const getModuleDisplayName = (module: string) => {
  const moduleMap: Record<string, string> = {
    'politics': '政治理论',
    'commonSense': '常识判断',
    'language': '言语理解与表达',
    'quantity': '数量关系',
    'judgment': '判断推理',
    'dataAnalysis': '资料分析'
  };
  
  // 对于判断推理模块，如果有分类信息，需要特殊处理
  if (module === 'judgment') {
    // 查找该模块的第一个题目，获取其分类信息
    const judgmentQuestions = groupedQuestions.value[module];
    if (judgmentQuestions && judgmentQuestions.length > 0) {
      const firstQuestion = judgmentQuestions[0];
      if (firstQuestion.category) {
        return `${moduleMap[module]}-${firstQuestion.category}`;
      }
      // 如果category为空，则默认显示"图形推理"
      return `${moduleMap[module]}-图形推理`;
    }
  }
  
  return moduleMap[module] || module;
};

// 根据题目ID获取索引
const getQuestionIndex = (questionId: number) => {
  return paperQuestions.value.findIndex(q => q.id === questionId);
};

// 清理HTML内容，防止XSS攻击，并为题目内容中的图片设置适中的尺寸
const sanitizeQuestionContentHtml = (html: string) => {
  if (!html) return '';
  // 使用htmlUtils中的modifyQuestionContentImageSizeInHTML函数处理题目内容HTML
  return modifyQuestionContentImageSizeInHTML(html);
};

// 清理选项HTML内容，防止XSS攻击，并为选项中的图片设置较小的尺寸
const sanitizeOptionHtml = (html: string) => {
  if (!html) return '';
  // 使用htmlUtils中的modifyOptionImageSizeInHTML函数处理选项HTML内容
  return modifyOptionImageSizeInHTML(html);
};

// 获取试卷数据
const fetchPaperData = async () => {
  try {
    // 从路由参数获取试卷ID和设置
    const paperId = route.query.paperId as string
    const mode = route.query.mode as string
    const continueProgress = route.query.continueProgress === 'true'
    showAnswers.value = route.query.showAnswers === 'true'
    
    // 获取试卷信息
    const paperRes: any = await paperApi.getPaperById(Number(paperId))
    if (paperRes.code === 200) {
      paperInfo.value = paperRes.data
    }
    
    // 获取试卷分值信息（如果存在）
    const paperScoreId = route.query.paperScoreId as string
    if (paperScoreId) {
      try {
        const paperScoreRes: any = await paperScoreApi.getPaperScoreById(Number(paperScoreId))
        if (paperScoreRes.code === 200) {
          paperScoreInfo.value = paperScoreRes.data
        }
      } catch (error) {
        console.log('未找到试卷分值信息')
      }
    } else {
      // 尝试从sessionStorage获取试卷分值信息
      try {
        const paperScoreData = sessionStorage.getItem(`paperScore_${paperId}`)
        if (paperScoreData) {
          const paperScoreRelation = JSON.parse(paperScoreData)
          if (paperScoreRelation.paperScoreInfo) {
            paperScoreInfo.value = paperScoreRelation.paperScoreInfo
          }
        }
      } catch (error) {
        console.log('未找到试卷分值信息')
      }
    }
    
    // 获取试卷题目（从后端获取真实数据）
    const questionsRes: any = await paperApi.getPaperQuestions(Number(paperId))
    if (questionsRes.code === 200) {
      // 根据实际返回的数据结构处理题目
      // 后端返回的数据结构是按模块分类的，需要合并成一个数组
      const allQuestions: any[] = [];
      if (questionsRes.data) {
        // 遍历所有模块的题目并合并到一个数组中
        Object.keys(questionsRes.data).forEach(module => {
          if (Array.isArray(questionsRes.data[module])) {
            questionsRes.data[module].forEach((question: any, index: number) => {
              // 处理选项数据，确保是对象数组格式
              let options = question.options;
              if (typeof question.options === 'string') {
                try {
                  options = JSON.parse(question.options);
                } catch (e) {
                  // 如果解析失败，保持原样
                  options = question.options;
                }
              }
              
              // 如果options是数组，确保每个选项是对象格式
              if (Array.isArray(options)) {
                options = options.map(option => {
                  if (typeof option === 'string') {
                    return { content: option };
                  }
                  return option;
                });
              } 
              // 如果options是对象，转换为数组格式
              else if (typeof options === 'object' && options !== null) {
                const optionsArray = [];
                for (const key in options) {
                  if (options.hasOwnProperty(key)) {
                    optionsArray.push({ content: options[key] });
                  }
                }
                options = optionsArray;
              }
              
              // 确保题目对象有正确的type字段（使用模块名称作为type字段值）
              // 同时保留原始的questionType字段用于选项显示判断
              allQuestions.push({
                ...question,
                type: module, // 使用模块名称作为type字段值
                questionType: question.questionType || question.type, // 保留原始题型
                options: options,
                category: question.category // 保留category字段
              });
            });
          }
        });
      }
      
      // 添加调试日志，检查题目分组是否正确
      console.log('处理后的题目数据:', allQuestions);
      // 按模块分组显示题目数量
      const moduleCounts: Record<string, number> = {};
      allQuestions.forEach(question => {
        const module = question.type;
        if (!moduleCounts[module]) {
          moduleCounts[module] = 0;
        }
        moduleCounts[module]++;
      });
      console.log('各模块题目数量:', moduleCounts);
      
      // 检查判断推理模块的category信息
      const judgmentQuestions = allQuestions.filter(q => q.type === 'judgment');
      if (judgmentQuestions.length > 0 && judgmentQuestions[0].category) {
        console.log('判断推理模块第一个题目的category:', judgmentQuestions[0].category);
      }
      
      paperQuestions.value = allQuestions;
      
      // 检查是否有题目，如果没有题目则不允许开始测验
      if (!paperQuestions.value || paperQuestions.value.length === 0) {
        ElMessage.error('该试卷没有题目，无法开始测验')
        router.back()
        return
      }
    } else {
      ElMessage.error('获取试卷题目失败')
      router.back()
      return
    }
    
    // 如果是继续答题,恢复之前的答题进度
    if (continueProgress) {
      const progressKey = `paper_progress_${paperId}`
      const savedData = localStorage.getItem(progressKey)
      if (savedData) {
        try {
          const progress = JSON.parse(savedData)
          console.log('从localStorage读取的进度数据:', progress)
              
          // 恢复用户答案 - 使用逐个赋值确保响应式更新
          if (progress.userAnswers) {
            Object.keys(progress.userAnswers).forEach(key => {
              userAnswers[key] = progress.userAnswers[key]
            })
            console.log('恢复后的userAnswers:', userAnswers)
            console.log('已恢复答案数量:', Object.keys(userAnswers).length)
          }
              
          // 恢复当前题目索引
          currentQuestionIndex.value = progress.currentQuestionIndex || 0
          console.log('恢复的当前题目索引:', currentQuestionIndex.value)
              
          // 恢复剩余时间
          if (progress.remainingTime && progress.remainingTime > 0) {
            endTime.value = Date.now() + progress.remainingTime
            console.log('恢复的剩余时间(秒):', Math.round(progress.remainingTime / 1000))
          } else {
            endTime.value = Date.now() + paperInfo.value.totalDuration * 60 * 1000
            console.log('使用默认总时长')
          }
              
          // 使用nextTick确保答题卡正确渲染
          nextTick(() => {
            console.log('答题卡渲染完成,已答题数:', answeredCount.value)
            ElMessage.success(`已恢复答题进度,继续第${currentQuestionIndex.value + 1}题`)
          })
        } catch (error) {
          console.error('恢复答题进度失败:', error)
          // 恢复失败，使用默认时间
          endTime.value = Date.now() + paperInfo.value.totalDuration * 60 * 1000
          ElMessage.warning('恢复答题进度失败,将从头开始')
        }
      } else {
        console.log('未找到保存的答题进度')
        // 没有找到保存的进度，使用默认时间
        endTime.value = Date.now() + paperInfo.value.totalDuration * 60 * 1000
        ElMessage.info('未找到保存的进度,开始新的答题')
      }
    } else {
      // 设置考试结束时间
      endTime.value = Date.now() + paperInfo.value.totalDuration * 60 * 1000
    }
    
    // 不再显示通用的成功消息,因为有更详细的提示
    if (!continueProgress) {
      ElMessage.success('试卷加载成功')
    }
  } catch (error) {
    console.error('试卷加载失败:', error);
    ElMessage.error('试卷加载失败')
    router.back()
  }
}

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < getSortedQuestions.value.length - 1) {
    currentQuestionIndex.value++
  }
}

// 获取按模块排序的题目数组
const getSortedQuestions = computed(() => {
  const sortedQuestions: Question[] = [];
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  
  // 按照模块顺序添加题目
  moduleOrder.forEach(module => {
    if (groupedQuestions.value[module]) {
      sortedQuestions.push(...groupedQuestions.value[module]);
    }
  });
  
  // 添加其他未在顺序列表中的模块
  Object.keys(groupedQuestions.value).forEach(module => {
    if (!moduleOrder.includes(module)) {
      sortedQuestions.push(...groupedQuestions.value[module]);
    }
  });
  
  return sortedQuestions;
});

// 跳转到指定题目
const jumpToQuestion = (index: number) => {
  console.log('跳转到题目索引:', index);
  if (index >= 0 && index < getSortedQuestions.value.length) {
    currentQuestionIndex.value = index;
    console.log('当前题目ID:', getSortedQuestions.value[index]?.id);
    console.log('当前题目内容:', getSortedQuestions.value[index]?.content?.substring(0, 50) + '...');
  } else {
    console.error('无效的题目索引:', index);
  }
};

// 获取答题卡项目类名
const getSheetItemClass = (question: Question, module: string, indexInModule: number) => {
  const classes = [];
  
  // 构建答案键
  const answerKey = `${module}-${question.id}`
  
  // 如果用户已答该题 - 使用模块+ID作为键
  if (userAnswers[answerKey]) {
    classes.push('answered');
    
    // 检查答案是否正确
    const userAnswer = userAnswers[answerKey];
    let isCorrect = false;
    
    // 根据题目类型判断答案是否正确
    if (question.questionType === 'single' || question.questionType === 'single_choice' || 
        question.questionType === 'trueFalse' || question.questionType === 'true_false') {
      isCorrect = userAnswer === question.correctAnswer;
    } else if (question.questionType === 'multiple' || question.questionType === 'multiple_choice') {
      const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : [];
      const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : [];
      isCorrect = JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort());
    }
    
    // 根据答案正确性添加相应的类
    if (isCorrect) {
      classes.push('correct');
    } else {
      classes.push('wrong');
    }
  }
  
  // 如果是当前题 - 需要确保只有一道题被标记为当前题
  // 通过比较题目ID和模块来确保准确性
  if (currentQuestion.value && 
      question.id === currentQuestion.value.id && 
      module === currentQuestion.value.type) {
    classes.push('current');
  }
  
  return classes;
};

// 答题卡点击事件
const onAnswerSheetClick = (questionId: number, module: string, indexInModule: number) => {
  console.log('答题卡点击 - 题目ID:', questionId, '模块:', module, '模块内索引:', indexInModule);
  // 直接根据模块和模块内索引计算在排序后数组中的位置
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  let totalCount = 0;
  
  // 找到目标模块在顺序中的位置
  const targetModuleIndex = moduleOrder.indexOf(module);
  
  // 如果目标模块不在标准模块顺序中，则在其他模块中查找
  if (targetModuleIndex === -1) {
    // 计算标准模块的总题目数
    for (let i = 0; i < moduleOrder.length; i++) {
      if (groupedQuestions.value[moduleOrder[i]]) {
        totalCount += groupedQuestions.value[moduleOrder[i]].length;
      }
    }
    // 在其他模块中查找目标模块
    const otherModules = Object.keys(groupedQuestions.value).filter(m => !moduleOrder.includes(m));
    const targetOtherModuleIndex = otherModules.indexOf(module);
    if (targetOtherModuleIndex !== -1) {
      for (let i = 0; i < targetOtherModuleIndex; i++) {
        totalCount += groupedQuestions.value[otherModules[i]].length;
      }
    }
  } else {
    // 计算目标模块之前所有模块的题目数量
    for (let i = 0; i < targetModuleIndex; i++) {
      const prevModule = moduleOrder[i];
      if (groupedQuestions.value[prevModule]) {
        totalCount += groupedQuestions.value[prevModule].length;
      }
    }
  }
  
  // 计算最终索引：之前模块的题目总数 + 当前模块内的索引
  const index = totalCount + indexInModule;
  console.log('在排序后数组中的索引:', index);
  jumpToQuestion(index);
};

// 时间到处理
const onTimeUp = () => {
  ElMessageBox.alert('考试时间已到，即将自动交卷', '提示', {
    confirmButtonText: '确定',
    callback: () => {
      submitPaper()
    }
  })
}

// 交卷
const submitPaper = () => {
  showSubmitDialog.value = true
}

// 用户存储
const userStore = useUserStore()

// 确认交卷
const confirmSubmit = async () => {
  try {
    // 检查用户是否登录
    if (!userStore.userInfo || !userStore.userInfo.userId) {
      ElMessage.error('用户未登录或用户信息不完整')
      // 不再跳转到登录页面，而是关闭对话框并提示用户
      showSubmitDialog.value = false
      return
    }
    
    // 清除保存的答题进度（交卷后不再需要）
    const paperId = route.query.paperId as string
    if (paperId) {
      const progressKey = `paper_progress_${paperId}`
      localStorage.removeItem(progressKey)
    }
    
    // 停止自动保存
    stopAutoSave()
    
    // 计算测验结果
    let correctCount = 0
    let wrongCount = 0
    let unansweredCount = 0
    let totalScore = 100 // 默认总分100分
    let score = 0
    
    // 如果有试卷分值信息，则使用试卷分值计算
    if (paperScoreInfo.value && paperScoreInfo.value.details) {
      // 根据试卷分值详情计算得分
      totalScore = paperScoreInfo.value.totalScore || 100
      
      // 按模块计算得分
      const moduleScores: Record<string, { correct: number; total: number; scorePerQuestion: number }> = {}
      
      // 初始化各模块得分信息
      paperScoreInfo.value.details.forEach((detail: any) => {
        moduleScores[detail.module] = {
          correct: 0,
          total: detail.questionCount || 0,
          scorePerQuestion: detail.scorePerQuestion || 0
        }
      })
      
      // 统计各模块正确题数
      Object.keys(userAnswers).forEach(key => {
        const [module, idStr] = key.split('-')
        const questionId = Number(idStr)
        const question = paperQuestions.value.find(q => q.id === questionId && q.type === module)
        if (!question) return
        
        const userAnswer = userAnswers[key]
        if (!userAnswer) {
          unansweredCount++
          return
        }
        
        // 获取题目类型，优先使用questionType，如果没有则使用type
        const questionType = question.questionType || question.type
        
        let isCorrect = false
        
        // 单选题和判断题的判断逻辑
        if (questionType === 'single' || questionType === 'single_choice' || 
            questionType === 'trueFalse' || questionType === 'true_false') {
          isCorrect = userAnswer === question.correctAnswer
        } 
        // 多选题的判断逻辑
        else if (questionType === 'multiple' || questionType === 'multiple_choice') {
          const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : []
          const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : []
          isCorrect = JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort())
        }
        
        if (isCorrect) {
          correctCount++
          if (moduleScores[module]) {
            moduleScores[module].correct++
          }
        } else {
          wrongCount++
        }
      })
      
      // 计算总得分
      let totalPoints = 0
      Object.keys(moduleScores).forEach(module => {
        const moduleInfo = moduleScores[module]
        totalPoints += moduleInfo.correct * moduleInfo.scorePerQuestion
      })
      
      score = Math.round(totalPoints)
      unansweredCount = paperQuestions.value.length - correctCount - wrongCount
    } else {
      // 使用原有计算方式
      correctCount = Object.keys(userAnswers).filter(key => {
        // 从键中提取模块和ID
        const [module, idStr] = key.split('-')
        const questionId = Number(idStr)
        const question = paperQuestions.value.find(q => q.id === questionId && q.type === module)
        if (!question) return false
        
        const userAnswer = userAnswers[key]
        if (!userAnswer) return false
        
        // 获取题目类型，优先使用questionType，如果没有则使用type
        const questionType = question.questionType || question.type
        
        // 单选题和判断题的判断逻辑
        if (questionType === 'single' || questionType === 'single_choice' || 
            questionType === 'trueFalse' || questionType === 'true_false') {
          return userAnswer === question.correctAnswer
        } 
        // 多选题的判断逻辑
        else if (questionType === 'multiple' || questionType === 'multiple_choice') {
          const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : []
          const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : []
          return JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort())
        }
        return true
      }).length
      
      wrongCount = Object.keys(userAnswers).filter(key => {
        // 从键中提取模块和ID
        const [module, idStr] = key.split('-')
        const questionId = Number(idStr)
        const question = paperQuestions.value.find(q => q.id === questionId && q.type === module)
        if (!question) return false
        
        const userAnswer = userAnswers[key]
        if (!userAnswer) return false
        
        // 获取题目类型，优先使用questionType，如果没有则使用type
        const questionType = question.questionType || question.type
        
        // 单选题和判断题的判断逻辑
        if (questionType === 'single' || questionType === 'single_choice' || 
            questionType === 'trueFalse' || questionType === 'true_false') {
          return userAnswer !== question.correctAnswer
        } 
        // 多选题的判断逻辑
        else if (questionType === 'multiple' || questionType === 'multiple_choice') {
          const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : []
          const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : []
          return JSON.stringify(userAnswersArray.sort()) !== JSON.stringify(correctAnswersArray.sort())
        }
        return false
      }).length
      
      unansweredCount = paperQuestions.value.length - Object.keys(userAnswers).length
      score = Math.round((correctCount / paperQuestions.value.length) * totalScore)
    }
    
    const timeSpent = paperInfo.value.totalDuration * 60 - Math.round((endTime.value - Date.now()) / 1000)

    // 转换userAnswers格式，将"模块-题目ID"键转换为仅题目ID键
    const formattedUserAnswers: Record<number, any> = {}
    Object.keys(userAnswers).forEach(key => {
      const [module, idStr] = key.split('-')
      const questionId = Number(idStr)
      formattedUserAnswers[questionId] = userAnswers[key]
    })

    // 准备计分方式信息
    let scoringMethod = 'auto'; // 默认为系统自动计分
    let scoringDescription = '系统默认计分(每题1分)';

    // 检查是否使用了试卷分值配置
    if (paperScoreInfo.value && paperScoreInfo.value.examName) {
      scoringMethod = 'custom';
      scoringDescription = `${paperScoreInfo.value.examName} - ${paperScoreInfo.value.subject} (总分${paperScoreInfo.value.totalScore}分)`;
    }

    // 创建试卷测验结果
    const paperResult = {
      userId: userStore.userInfo.userId,
      paperId: paperInfo.value.id,
      score: score,
      totalScore: totalScore,
      correctCount: correctCount,
      wrongCount: wrongCount,
      unansweredCount: unansweredCount,
      timeSpent: timeSpent,
      startTime: new Date(Date.now() - timeSpent * 1000), // 这里应该记录实际的开始时间
      endTime: new Date(),
      createTime: new Date(), // 添加创建时间字段
      userAnswers: formattedUserAnswers, // 使用转换后的格式
      scoringMethod: scoringMethod, // 计分方式
      scoringDescription: scoringDescription // 计分说明
    }
    
    // 提交试卷结果
    const res: any = await paperResultApi.createPaperResult(paperResult)
    if (res.code === 200) {
      // 不再单独显示"试卷提交成功"提示，而是整合到跳转后的页面中显示
      showSubmitDialog.value = false
      
      // 记录错题
      const wrongQuestions: any[] = [];
      
      // 遍历所有题目，找出答错的题目
      paperQuestions.value.forEach(question => {
        const userAnswer = userAnswers[`${question.type}-${question.id}`];
        if (!userAnswer) return;
        
        // 获取题目类型，优先使用questionType，如果没有则使用type
        const questionType = question.questionType || question.type;
        
        let isAnswerCorrect = false;
        
        // 单选题和判断题的判断逻辑
        if (questionType === 'single' || question.questionType === 'single_choice' || 
            question.questionType === 'trueFalse' || question.questionType === 'true_false') {
          isAnswerCorrect = userAnswer === question.correctAnswer;
        } 
        // 多选题的判断逻辑
        else if (questionType === 'multiple' || question.questionType === 'multiple_choice') {
          const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : [];
          const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : [];
          isAnswerCorrect = JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort());
        }
        
        // 如果答案错误，添加到错题列表
        if (!isAnswerCorrect) {
          wrongQuestions.push({
            questionId: question.id,
            userId: userStore.userInfo.userId,
            questionType: questionType || 'single', // 确保有题目类型
            title: question.content ? question.content.substring(0, 50) + (question.content.length > 50 ? '...' : '') : '', // 截取前50个字符作为标题
            content: question.content || '',
            options: formatOptionsForDatabase(question.options),
            correctAnswer: question.correctAnswer || (question.correctAnswers ? (Array.isArray(question.correctAnswers) ? question.correctAnswers.join(',') : question.correctAnswers) : ''),
            difficulty: '中等',
            explanation: (question as any).analysis || (question as any).explanation || '',
            category: question.category || '', // 使用题目分类作为分类
            subCategory: '',
            module: question.type || '', // 使用题目类型作为模块
            status: 1, // 默认状态为1
            createTime: new Date(),
            updateTime: new Date(),
          });
        }
      });
      
      // 批量添加错题
      if (wrongQuestions.length > 0) {
        try {
          await Promise.all(wrongQuestions.map(wq => addWrongQuestion(wq)));
          console.log(`成功添加 ${wrongQuestions.length} 道错题到错题本`);
          ElMessage.info(`已记录 ${wrongQuestions.length} 道错题到错题本`);
        } catch (error) {
          console.error('添加错题失败:', error);
          ElMessage.error('错题记录保存失败');
        }
      }
      
      // 保存试卷分值信息到sessionStorage，以便结果页面使用
      if (paperScoreInfo.value) {
        sessionStorage.setItem('currentPaperScore', JSON.stringify(paperScoreInfo.value));
      }
      
      // 跳转到结果页面
      router.push({
        path: '/paper-test/result',
        query: {
          paperId: paperInfo.value.id.toString(),
          // 添加提交成功的标识，用于在结果页面显示整合的提示信息
          submitSuccess: 'true'
        }
      })
    } else {
      ElMessage.error(res.message || '提交失败，请重试')
    }
  } catch (error: any) {
    console.error('试卷提交失败:', error)
    ElMessage.error('提交失败，请重试')
  }
}

// 组件挂载时获取试卷数据
onMounted(() => {
  fetchPaperData()
  // 设置自动保存答题进度
  startAutoSave()
})

// 组件卸载时清理
onUnmounted(() => {
  // 清理定时器
  stopAutoSave()
})

// 自动保存定时器
let autoSaveTimer: number | null = null

// 开始自动保存
const startAutoSave = () => {
  // 每30秒自动保存一次答题进度
  autoSaveTimer = window.setInterval(() => {
    saveProgress()
  }, 30000)
}

// 停止自动保存
const stopAutoSave = () => {
  if (autoSaveTimer) {
    clearInterval(autoSaveTimer)
    autoSaveTimer = null
  }
}

// 保存答题进度
const saveProgress = () => {
  const paperId = route.query.paperId as string
  if (!paperId) return
  
  const progressKey = `paper_progress_${paperId}`
  const progress = {
    paperId: paperId,
    userAnswers: { ...userAnswers },
    currentQuestionIndex: currentQuestionIndex.value,
    remainingTime: endTime.value - Date.now(),
    answeredCount: answeredCount.value,
    savedTime: new Date().toISOString()
  }
  
  try {
    localStorage.setItem(progressKey, JSON.stringify(progress))
    console.log('答题进度已保存:', {
      试卷ID: paperId,
      已答题数: progress.answeredCount,
      当前题目索引: progress.currentQuestionIndex,
      剩余时间_秒: Math.round(progress.remainingTime / 1000),
      保存时间: progress.savedTime
    })
  } catch (error) {
    console.error('保存答题进度失败:', error)
  }
}

// 返回设置页面
const goToSettings = () => {
  // 保存当前答题进度
  saveProgress()
  ElMessage.success('答题进度已保存')
  router.push('/paper-test/settings');
}

// 格式化选项以存储到数据库
const formatOptionsForDatabase = (options: any) => {
  // 如果没有选项，返回空字符串
  if (!options) return '';
  
  // 如果已经是字符串，直接返回
  if (typeof options === 'string') return options;
  
  // 如果是数组格式 [{content: "选项1"}, {content: "选项2"}]
  if (Array.isArray(options)) {
    const formattedOptions: Record<string, string> = {};
    options.forEach((option, index) => {
      const key = String.fromCharCode(65 + index); // A, B, C, D...
      formattedOptions[key] = option.content || option;
    });
    return JSON.stringify(formattedOptions);
  }
  
  // 如果是对象格式 {A: "选项1", B: "选项2"}
  if (typeof options === 'object') {
    return JSON.stringify(options);
  }
  
  // 其他情况，转换为字符串
  return String(options);
}

// 获取当前题目的连续编号
const getCurrentQuestionContinuousNumber = () => {
  if (!currentQuestion.value) return 0;
  
  // 找到当前题目所在的模块
  const currentModule = currentQuestion.value.type;
  if (!currentModule) return currentQuestionIndex.value + 1;
  
  // 找到当前题目在模块中的索引
  const moduleQuestions = groupedQuestions.value[currentModule];
  if (!moduleQuestions) return currentQuestionIndex.value + 1;
  
  const indexInModule = moduleQuestions.findIndex(q => q.id === currentQuestion.value.id);
  if (indexInModule === -1) return currentQuestionIndex.value + 1;
  
  // 使用已有的函数计算连续编号
  return getContinuousQuestionNumber(currentModule, indexInModule);
};

// 获取连续的题目编号
const getContinuousQuestionNumber = (module: string, indexInModule: number) => {
  // 计算当前模块之前所有模块的题目总数
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  let totalCount = 0;
  
  // 找到当前模块在顺序中的位置
  const currentModuleIndex = moduleOrder.indexOf(module);
  
  // 计算之前所有模块的题目数量
  for (let i = 0; i < currentModuleIndex; i++) {
    const prevModule = moduleOrder[i];
    if (groupedQuestions.value[prevModule]) {
      totalCount += groupedQuestions.value[prevModule].length;
    }
  }
  
  // 加上当前模块内的索引+1（因为索引从0开始）
  return totalCount + indexInModule + 1;
};

</script>

<style scoped>
.paper-test-practice {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  text-align: left !important;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 新增主内容区样式 */
.main-content {
  display: flex;
  width: 100%;
  max-width: 1200px;
  gap: 20px;
  margin-bottom: 20px;
  align-items: flex-start; /* 恢复默认对齐方式 */
  min-height: auto; /* 取消最小高度限制，让内容自适应 */
  height: 600px; /* 设置固定高度以确保左右区域等高 */
  max-height: 600px; /* 设置最大高度 */
}

/* 覆盖 Element Plus 卡片的默认样式 */
.paper-test-practice .el-card {
  text-align: left !important;
  width: 100%;
  max-width: 1200px;
  margin-bottom: 20px;
}

.paper-test-practice .el-card__body {
  text-align: left !important;
}

.paper-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  text-align: left !important;
  width: 100%;
  max-width: 1200px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.paper-header :deep(.el-card__body) {
  padding: 20px;
}

.header-wrapper {
  width: 100%;
}

.paper-title {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 2px solid rgba(255, 255, 255, 0.3);
}

.paper-title h2 {
  margin: 0 0 5px 0;
  font-size: 24px;
  font-weight: bold;
  color: white;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

.paper-subtitle {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  flex-wrap: wrap;
  gap: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  flex-wrap: wrap;
  gap: 15px;
}

.paper-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  flex: 1;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 8px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s;
}

.stat-item:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 20px;
  flex-shrink: 0;
}

.stat-text {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
}

.stat-text strong {
  color: white;
  font-size: 15px;
  margin-left: 4px;
}

.answered-count {
  color: #a0ffb8 !important;
}

.unanswered-count {
  color: #ffb8b8 !important;
}

.timer-section {
  display: flex;
  align-items: center;
  gap: 12px;
  white-space: nowrap;
  background: rgba(255, 255, 255, 0.1);
  padding: 12px 16px;
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.countdown-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding-right: 12px;
  border-right: 1px solid rgba(255, 255, 255, 0.3);
}

.countdown-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

/* 调整题目区域样式 */
.question-area {
  flex: 3;
  margin-bottom: 0;
  text-align: left !important;
  max-width: calc(100% - 220px);
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: none;
  overflow-y: auto;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.question-area:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.question-area :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px 20px;
  border-bottom: none;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  text-align: left !important;
  flex-wrap: wrap;
  gap: 10px;
}

.question-title-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: white;
}

.question-title-badge .el-icon {
  font-size: 18px;
}

.question-navigation {
  display: flex;
  gap: 10px;
}

.question-content {
  padding: 25px;
  text-align: left !important;
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow-y: visible;
  height: auto;
  background: #fafbfc;
}

.question-main {
  text-align: left !important;
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  height: auto;
  flex: 1;
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.question-title-container {
  flex: 1;
  overflow-y: visible;
  padding: 0 0 15px 0;
  border-bottom: 2px solid #e8edf3;
  margin-bottom: 20px;
}

.question-title {
  margin: 0 0 10px 0;
  font-size: 17px;
  line-height: 1.8;
  color: #303133;
  font-weight: 500;
}

.question-title img {
  max-width: 700px !important; /* 将题目内容图片调大 */
  max-height: 500px !important; /* 将题目内容图片调大 */
  height: auto;
  width: auto;
  object-fit: contain;
  display: block;
  margin: 5px 0;
}

.options-container {
  flex: none; /* 改为none，让容器根据内容自适应高度 */
  overflow-y: visible; /* 取消滚动条，让内容自然展开 */
  padding: 10px 0;
  height: auto; /* 确保高度自适应 */
}

.options-area {
  text-align: left !important;
  display: block;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  height: auto; /* 确保高度自适应 */
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 8px; /* 减小选项间距 */
  text-align: left !important;
  align-items: flex-start;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 0;
  height: auto; /* 确保高度自适应 */
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 6px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
  border: 1px solid #ebeef5;
  text-align: left !important;
  justify-content: flex-start !important;
  width: 100%;
  max-width: 800px;
  box-sizing: border-box;
  margin: 0;
  margin-right: 0 !important;
  align-self: flex-start;
  min-height: auto;
  height: auto;
}

.option-label {
  margin-right: 10px;
  min-width: 20px;
  flex-shrink: 0; /* 防止标签被压缩 */
}

.option-content {
  flex: 1;
  line-height: 1.5;
  text-align: left !important;
  max-width: 100%;
  height: auto;
  overflow: visible;
  font-size: 16px; /* 增大选项字体大小，提高可读性 */
}

.option-content img {
  max-width: 150px !important; /* 将选项图片调大 */
  max-height: 120px !important; /* 将选项图片调大 */
  height: auto;
  width: auto;
  object-fit: contain;
  display: block;
  margin: 5px 0;
}

/* 覆盖 Element Plus 的默认样式 */
.el-radio-group,
.el-checkbox-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  text-align: left !important;
  width: 100%;
  max-width: 800px;
  justify-content: flex-start;
  margin: 0 auto;
  height: auto; /* 确保高度自适应 */
}

.el-radio,
.el-checkbox {
  display: flex;
  align-items: flex-start; /* 修改为flex-start以适应高度自适应 */
  text-align: left !important;
  margin-right: 0 !important;
  margin-bottom: 8px; /* 减小选项底部间距 */
  width: 100%;
  max-width: 800px;
  justify-content: flex-start !important;
  align-self: flex-start;
  height: auto; /* 确保高度自适应 */
}

.el-radio__input,
.el-checkbox__input {
  margin-right: 10px;
  margin-top: 3px; /* 调整对齐 */
}

/* 调整答题卡样式 */
.answer-sheet {
  flex: 1;
  min-width: 250px;
  max-width: 320px;
  position: static;
  top: auto;
  right: auto;
  display: flex;
  flex-direction: column;
  height: 600px;
  max-height: 600px;
  overflow: visible;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.answer-sheet:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.answer-sheet :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px 20px;
  border-bottom: none;
}

.answer-sheet :deep(.el-card__body) {
  flex: 1;
  overflow: hidden;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.sheet-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sheet-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: white;
}

.sheet-title .el-icon {
  font-size: 18px;
}

.sheet-legend {
  display: flex;
  gap: 15px;
  font-size: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
}

.legend-dot.answered {
  background-color: #67c23a;
}

.legend-dot.current {
  background-color: #409eff;
}

.legend-text {
  color: rgba(255, 255, 255, 0.9);
}

.sheet-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 15px 20px 30px 15px;
}

.sheet-content::-webkit-scrollbar {
  width: 6px;
}

.sheet-content::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 3px;
}

.sheet-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.sheet-content::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}

.module-section {
  background: #f9fafb;
  border-radius: 10px;
  padding: 15px;
  transition: all 0.3s;
}

.module-section:hover {
  background: #f5f7fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.module-section:last-child {
  margin-bottom: 0;
}

.module-name {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
  border-radius: 8px;
  border-left: 3px solid #409eff;
}

.module-name-text {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.module-count {
  font-size: 12px;
  color: #909399;
  background: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: 500;
}

.module-sheet {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  padding: 5px;
}

.sheet-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 36px;
  border: 2px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: white;
  min-width: 36px;
  font-size: 13px;
  font-weight: 600;
  overflow: hidden;
}

.sheet-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 100%);
  opacity: 0;
  transition: opacity 0.3s;
}

.sheet-item:hover::before {
  opacity: 1;
}

.sheet-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.sheet-item-number {
  position: relative;
  z-index: 1;
}

.sheet-item.answered {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: white;
  border-color: #67c23a;
  box-shadow: 0 2px 6px rgba(103, 194, 58, 0.3);
}

.sheet-item.current {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: white;
  border-color: #409eff;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
  transform: scale(1.05);
}

.dialog-footer {
  text-align: right;
}

/* 导航按钮样式 */
.question-navigation-bottom {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 2px solid #e8edf3;
}

.navigation-buttons {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

/* 更强力的左对齐样式 */
.question-content *,
.options-list *,
.option-item *,
.option-content * {
  text-align: left !important;
  justify-content: flex-start !important;
  align-items: flex-start !important;
}

/* 特别针对选项容器 */
.options-list .el-radio,
.options-list .el-checkbox {
  display: flex;
  justify-content: flex-start !important;
  align-items: flex-start !important;
  width: 100%;
  text-align: left !important;
  height: auto;
}



/* 判断题 */
.true-false-area .options-list {
  flex-direction: row;
  gap: 10px; /* 减小判断题选项间距 */
  max-width: 800px;
  margin: 0 auto;
  height: auto; /* 确保高度自适应 */
}

.true-false-area .option-item {
  margin-right: 10px; /* 减小判断题选项右边距 */
  max-width: 300px;
  align-items: flex-start; /* 修改为flex-start以适应高度自适应 */
  height: auto; /* 确保高度自适应 */
}

.true-false-area .options-list,
.fill-blank-area,
.short-answer-area {
  flex: none; /* 改为none，让容器根据内容自适应高度 */
  overflow-y: visible; /* 取消滚动条，让内容自然展开 */
  padding: 10px 0;
  height: auto; /* 确保高度自适应 */
}

/* 填空题 */
.fill-blank-area {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 10px 0;
}

.fill-blank-area .el-input {
  width: 300px;
  max-width: 100%;
}

/* 简答题 */
.short-answer-area {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 10px 0;
}

.short-answer-area .el-input {
  width: 100%;
  max-width: 800px;
}

.question-analysis {
  margin-top: 20px;
}

.question-analysis img {
  max-width: 700px !important; /* 将题目内容图片调大 */
  max-height: 500px !important; /* 将题目内容图片调大 */
  height: auto;
  width: auto;
  object-fit: contain;
  display: block;
  margin: 5px 0;
}

/* 为Element Plus组件中的标签添加样式控制 */
.options-list .el-radio__label,
.options-list .el-checkbox__label {
  display: flex;
  align-items: flex-start;
  width: 100%;
  height: auto;
  line-height: 1.5;
  padding: 0;
  font-size: 16px; /* 增大选项标签字体大小，提高可读性 */
}

/* 为Element Plus组件中的图片添加样式控制 */
.options-list .el-radio__label img,
.options-list .el-checkbox__label img {
  max-width: 150px !important; /* 将选项图片调大 */
  max-height: 120px !important; /* 将选项图片调大 */
  height: auto;
  width: auto;
  object-fit: contain;
  display: block;
  margin: 5px 0;
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    min-height: auto; /* 在小屏幕上使用自适应高度 */
  }
  
  .question-area {
    max-width: 100%;
    max-height: none; /* 在小屏幕上移除最大高度限制 */
  }
  
  .answer-sheet {
    width: 100%;
    margin-top: 20px;
    height: auto; /* 在小屏幕上使用自适应高度 */
    max-height: none; /* 在小屏幕上移除最大高度限制 */
  }
  
  .paper-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .paper-stats {
    flex-wrap: wrap;
  }
}

@media (max-width: 1200px) {
  .answer-sheet {
    position: static;
    width: 200px;
    max-width: 200px;
    margin: 0;
    height: auto; /* 使用自适应高度 */
    max-height: none; /* 移除最大高度限制 */
    overflow-y: hidden; /* 移除外部滚动条，只保留内部滚动条 */
    padding: 10px 0px 10px 10px; /* 进一步缩小右侧边距 */
  }
  
  .sheet-content {
    grid-template-columns: repeat(5, 1fr);
    gap: 8px;
    padding-right: 10px; /* 调整右侧内边距，避免滚动条紧贴答题项 */
    padding-bottom: 30px; /* 调整底部内边距，确保内容不被遮挡且视觉间距合理 */
  }
  
  .sheet-item {
    height: 25px;
    font-size: 12px;
  }
  
  .module-sheet {
    padding-bottom: 10px; /* 调整模块末尾底部边距 */
  }
}
</style>